var job_name_list = [];
// the timeout for ajax to request remote api
let polling_api_timeout = 1000 * 3;
// the timeout for check_status function to check if all request finished
let check_status_timeout = 1000 * 3;


$(function () {
    $("#batchSubmit").on('click', batchQuery);
});

function batchQuery(event) {
    $("tr.item").each(function (i, tr) {
        let job_name = $(".job_name", tr).text();
        let build_number = $(".build_number", tr).text();
        let queue_item = $(".queue_item", tr).text();
        job_name_list.push(job_name)
        //query the job's execution status
        getResp(job_name, build_number, queue_item)
    });
    // query if all jobs finished
    if (job_name_list.length != 0)
        check_status(job_name_list)
    else {
        alert("没有job被批量执行！查询结束")
    }
}

function getResp(job_name, build_number, queue_item) {

    let url = "/build/query_build_state?job_name=" + job_name + "&build_number="
        + build_number + "&queue_item=" + queue_item;
    $.ajax({
        type: "get",//请求方式
        url: url,//发送请求地址
        timeout: 3000,//超时时间：3秒
        dataType: "json",//设置返回数据的格式
        //请求成功后的回调函数 data为json格式
        success: function (data) {
            console.log(data);

            let progress;

            // set status text
            $("#status" + "_" + job_name).text(data['Status'] + ":" + data["Response"] + "%")
            // if data status is finished, adjust progress according to response status.
            if (data == null || data['Status'] == "Finished") {
                progress = 100;
                if (data["Response"] == "Success")
                    progress = 100;
                if (data["Response"] == "Failed")
                    progress = 0;
                $("#progress_bar" + "_" + job_name).attr("aria-valuenow", progress)
                $("#progress_bar" + "_" + job_name).css("width", progress + "%")

            }
            // else,adjust progress according to response value.and invoke by setTimeout again.
            else if (data['Status'] == "Building" || data['Status'] == "Waiting") {
                if (data['Status'] == "Waiting") {
                    progress = 0;
                }
                if (data['Status'] == "Building") {
                    progress = data["Response"];
                }
                $("#progress_bar" + "_" + job_name).attr("aria-valuenow", progress)
                $("#progress_bar" + "_" + job_name).css("width", progress + "%")
                setTimeout(getResp, polling_api_timeout, job_name, build_number, queue_item);
            }
        },
        //请求出错的处理
        error: function () {
            alert("请求出错");
        }
    });
}

function check_status(job_list) {
    let flag = true;
    job_list.forEach(function (item, index, array) {
        var status = $("#status" + "_" + item).text().split(":")[0]
        var temp_flag;
        if (status == "Finished") {
            temp_flag = true;
        } else {
            temp_flag = false;
        }
        flag = flag && temp_flag;
    });
    console.log(flag);
    // if flag is true, all jobs are finished.
    if (flag) {
        let task_number = $("#task_number").val();
        requestBuildJob("insert_redmine", task_number);
        alert("all finished!");
    }
    // still some job not finished. invoke check function in Timeout again.
    else {
        setTimeout(check_status, check_status_timeout, job_name_list);
    }
}

function requestBuildJob(job_name, task_number) {
    let url;
    if (job_name == "insert_redmine")
        url = "/build/comment_on_redmine";
    $.ajax({
        type: "POST",//请求方式
        //提交的数据
        data: {task_number: task_number},
        url: url,//发送请求地址
        timeout: 3000,//超时时间：3秒
        dataType: "json",//设置返回数据的格式
        //请求成功后的回调函数 data为json格式
        success: function (data) {
            alert("在redmine上留言成功！");
        },
        //请求出错的处理
        error: function () {
            alert("请求出错");
        }
    });
}